
var Test = {};

(function(jQuery){ 
	jQuery.fn.extend({  
		elastic: function() {
		
		
			return this.each( function() {
				
				var $textarea = jQuery(this),
					curHeight = 0,
					minHeight,
					borderBox,
					maxHeight,
					spacing,
					$clone,
					lineHeight;
			

				$textarea.bind('keyup focus', function(){recalculate()});
				$textarea.bind('paste', function(){paste()});

				if ($textarea.val() !== '')
				{
					recalculate();
				}
				
				
				function recalculate()
				{
					var input = textarea = $textarea.get(0),
						clone,
						height,
						pos;

					if ($textarea.val() === '')
					{
						$textarea.css({
							'overflow': 'hidden',
							'height': ''
						});
						curHeight = 0;
						return;
					}

					if (!minHeight)
					{
						borderBox = ($textarea.css('-moz-box-sizing') == 'border-box' || $textarea.css('box-sizing') == 'border-box');
						minHeight = (borderBox ? $textarea.outerHeight() : textarea.clientHeight);

						if (!minHeight)
						{
							return;
						}

						maxHeight = parseInt($textarea.css('max-height'), 10);
						spacing = (borderBox ? $textarea.outerHeight() - $textarea.innerHeight() : 0);
					}

					if (!$clone)
					{
						$clone = $('<textarea />').css({
							position: 'absolute',
							left: '-10000px',
							visibility: 'hidden',
							width: textarea.clientWidth,
							height: '1px',
							'font-size': $textarea.css('font-size'),
							'font-family': $textarea.css('font-family'),
							'font-weight': $textarea.css('font-weight'),
							'line-height': $textarea.css('line-height'),
							'word-wrap': $textarea.css('word-wrap')
						}).attr('tabindex', -1).val(' ');

						$clone.appendTo(document.body);

						lineHeight =  $clone.get(0).scrollHeight;
					}

					$clone.val($textarea.val());
					clone = $clone.get(0);

					height = Math.max(minHeight, clone.scrollHeight + lineHeight + spacing);

					if (height < maxHeight)
					{
						if (curHeight != height)
						{
							input = $textarea.get(0);
							if (curHeight == maxHeight && input.setSelectionRange)
							{
								pos = input.selectionStart;
							}

							$textarea.css({
								'overflow': 'hidden',
								'height': height + 'px'
							});

							if (curHeight == maxHeight && input.setSelectionRange)
							{
								input.setSelectionRange(pos, pos);
							}

							curHeight = height;
						}
					}
					else
					{
						if (curHeight != maxHeight)
						{
							input = $textarea.get(0);
							if (input.setSelectionRange)
							{
								pos = input.selectionStart;
							}

							$textarea.css({
								'overflow': 'auto',
								'height': maxHeight + 'px'
							});
							
							

							if (input.setSelectionRange)
							{
								input.setSelectionRange(pos, pos);
							}

							curHeight = maxHeight;
						}
					}
				}
				
				function paste()
				{
					setTimeout('recalculate', 100);
				}
				
				
			});
			
        } 
    }); 
})(jQuery);